//
//  OTAVc.m
//  CareRingApp
//
//  Created by Linktop on 2022/8/30.
//
//  升级流程 :1 初始状态 OTA_STATE_CHECKING_INIT
//  2 检查到充电 OTA_STATE_CHECKING_CHARGE
//  3 下发升级包 OTA_STATE_UPDATING
//  4 等待结束
//  5 重连设备 OTA_STATE_RECONNECTING
//  6 设备重连上, 成功 OTA_STATE_FINISH
//


//#import <YYKit/YYKit.h>
#import "CAOTAVc.h"
#import "ConfigModel.h"
//#import "DeviceCenter.h"
#import "CARingSDK.h"
//#include "BindParameterHeader.h"
#import "SRfileTableViewController.h"
#import "UIViewController+Custom.h"
#import "LTPHud.h"
#import <Masonry/Masonry.h>
#import "NSObject+Tool.h"
#import "CABLeService.h"
#import "Colors.h"

typedef NS_ENUM(NSUInteger, CA_OTA_STATE) {
    CA_OTA_STATE_CHECKING_INIT = 1,
    CA_OTA_STATE_CHECKING_CHARGE,
    CA_OTA_STATE_UPDATING,
    CA_OTA_STATE_RECONNECTING, // 升级完成等待重连一次
    CA_OTA_STATE_FINISH,
};

@interface CAOTAVc ()<CABleScanProtocal, CABleDataProtocal, CAOTAProtocal>

@property(assign, nonatomic)CA_OTA_STATE otaState;
@property(assign, nonatomic)BOOL otaSucc;
//@property (nonatomic,strong) YYAnimatedImageView *YYImageView; // 充电动画

@property(strong, nonatomic)UIProgressView *progressView;
@property(strong, nonatomic)UILabel *tipsLabel;
@property(strong, nonatomic)UILabel *percentLabel;

@property(strong, nonatomic)NSString *waitRecDeviceMacaddr;
@property(strong, nonatomic)NSTimer *scanTimeoutTimer;

@end

@implementation CAOTAVc

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}
-(void)initUI
{
    WEAK_SELF
    [self customNavStyleNormal:@"OTA" BackBlk:^{
        STRONG_SELF
        if (self.otaState == CA_OTA_STATE_CHECKING_INIT ||
            self.otaState == CA_OTA_STATE_FINISH) {
            
        }
    }];
  
    UIView *emptyView = [UIView new];
    [self.view addSubview:emptyView];
    [self.view addSubview:self.tipsLabel];
    
    [self.tipsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(30.0f);
        make.leading.equalTo(self.view.mas_leading).offset(20);
        make.trailing.equalTo(self.view.mas_trailing).inset(20);
    }];
  
    [emptyView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(emptyView.superview.mas_centerX);
        make.centerY.equalTo(emptyView.superview.mas_centerY);
        make.width.equalTo(emptyView.superview.mas_width).multipliedBy(0.6);
        make.height.equalTo(emptyView.mas_width);
    }];
    
    self.otaState = CA_OTA_STATE_CHECKING_INIT; // 初始状态
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (CARingSDK.instance.bleOtaDelegate != self) {
        CARingSDK.instance.bleDataDelegate = self;
        CARingSDK.instance.blescanDelegate = self;
        CARingSDK.instance.bleOtaDelegate = self;
        self.ousideBleDiscovery.cAscanDelegate = self;
    }
    
    if ([CARingSDK.instance.currentDevice isConnected]
        && [CARingSDK.instance.currentDevice isCharging])
    {
        self.otaState = CA_OTA_STATE_CHECKING_CHARGE; //变更为充电状态
    }

}

-(void)setOtaState:(CA_OTA_STATE)otaState
{
    
    switch (otaState) {
        case CA_OTA_STATE_CHECKING_INIT:
        {
            if (_otaState != CA_OTA_STATE_CHECKING_INIT) {
//                [self arrowback:nil];
                self.tipsLabel.text = @"Connect your device to the charger and the firmware update will start automatically.";
                
                // 蓝牙指令查是否充电
                [CARingSDK.instance functionGetDeviceBattery];
                // 检查充电
                
                
                
            }
        }
            break;
        case CA_OTA_STATE_CHECKING_CHARGE:
        {
            if (_otaState != CA_OTA_STATE_CHECKING_CHARGE && _otaState < CA_OTA_STATE_CHECKING_CHARGE) {
                DebugNSLog(@"充电状态 file:%@", self.updateImageFileUrl);
                self.otaState = CA_OTA_STATE_UPDATING;
                return;
            }
            
        }
            
            break;
        case CA_OTA_STATE_UPDATING:
        {
            if (_otaState != CA_OTA_STATE_UPDATING) {
                dispatch_async(dispatch_get_main_queue(), ^{
//                    self.navigationItem.leftBarButtonItem = nil;
//                    [self cleanLeftBarButon];
                    self.tipsLabel.text = [NSString stringWithFormat:@"The device firmware is being updated, it will take about 1 minute, please do not close the %@ APP", [ConfigModel appName]];
                    
//                    [self.YYImageView setImage:nil];
//                    [self.YYImageView removeFromSuperview];
                    
                    [self.view addSubview:self.progressView];
                    [self.view addSubview:self.percentLabel];
                    [self.progressView mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.centerX.equalTo(self.progressView.superview.mas_centerX);
                        make.centerY.equalTo(self.progressView.superview.mas_centerY);
                        make.width.equalTo(self.progressView.superview.mas_width).multipliedBy(0.8);
                    }];
                    [self.percentLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.leading.trailing.equalTo(self.progressView);
                        make.bottom.equalTo(self.progressView.mas_top).inset(3);
                    }];
                    [CARingSDK.instance functionStartOta:self.updateImageFileUrl];
                    self.waitRecDeviceMacaddr = CARingSDK.instance.currentDevice.macAddress;
                });
                
            }
        }
            break;
            
        case CA_OTA_STATE_FINISH:
        {
            if (_otaState != CA_OTA_STATE_FINISH) {
                dispatch_async(dispatch_get_main_queue(), ^{
//                    self.navigationItem.leftBarButtonItem = nil;
//                    [self cleanLeftBarButon];
//                    [self arrowback:nil];
//                    [self.YYImageView setImage:nil];
//                    self.YYImageView.hidden = YES;
//                    [self.YYImageView removeFromSuperview];
                    [self.progressView removeFromSuperview];
                    [self.percentLabel removeFromSuperview];
                    [[LTPHud Instance] hideHud];
                });
               
            }
        }
            break;

        case CA_OTA_STATE_RECONNECTING:
        {
          
            if (_otaState != CA_OTA_STATE_RECONNECTING) {
                [[LTPHud Instance] showHud:@"Waiting for Ring..."]; // 菊花转
//                [[DeviceCenter instance] disconnectCurrentService];
                WEAK_SELF
                [self mainThreadDelayAfter:1 Blk:^{
                    
                    STRONG_SELF
                    if (strongSelf.ousideBleDiscovery) {
                        [strongSelf.ousideBleDiscovery startScanning];
                        DebugNSLog(@"ota finish , scaning to reconnect.");
                    } else {
                        [CARingSDK.instance startBleScanWithOption:nil];
                    }
                    
                    [strongSelf.scanTimeoutTimer invalidate];
                    strongSelf.scanTimeoutTimer = [NSTimer scheduledTimerWithTimeInterval:2 * 60 repeats:NO block:^(NSTimer * _Nonnull timer) {
                        STRONG_SELF
                        [LTPHud.Instance hideHud];
                        [strongSelf showAlertWarningWithTitle:@"Tips" Msg:@"No device is scanned." btnCancel:@"Ok" Compelete:^{
                            [strongSelf.navigationController popViewControllerAnimated:YES];
                        }];
                        
                        
                    }];
                    
                }];
              
            }
           
           
        }
            break;
        default:
        {}
            break;
    }
    _otaState = otaState;

}

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if (self.otaState != CA_OTA_STATE_CHECKING_CHARGE) { // 防止滑动退出
        return NO;
    }
    return YES;
}

#pragma mark --蓝牙代理

- (void)caBleCmdExcute:(EXCUTED_CMD)cmd Succ:(BOOL)isSucc Reason:(CA_CMD_EXECTE_ERROR_REASON)reason Data:(NSData *)originData
{
    
}

- (void)caBleDeviceBatteryLevel:(NSInteger)batteryLevel IsCharging:(BOOL)isCharging {
    
    if (isCharging) {
        self.otaState = CA_OTA_STATE_CHECKING_CHARGE;
    }
    
}

- (void)caBleDeviceDidReadyForReadAndWrite:(CABLeService*)service {
    if (self.otaState == CA_OTA_STATE_RECONNECTING) {
        [[LTPHud Instance] hideHud];
        // 提示升级成功
        WEAK_SELF
        [self showAlertWarningWithTitle:@"Tips" Msg:@"Firmware update successful!" btnOk:@"Ok" OkBLk:^{
            STRONG_SELF
            strongSelf.otaState = CA_OTA_STATE_FINISH;
            if (strongSelf.otaFinishBLK) {
                strongSelf.otaFinishBLK(YES);
            }
            
            [strongSelf.navigationController popViewControllerAnimated:YES];
        } CancelBtn:nil CancelBlk:nil Compelete:nil];
        
        [CARingSDK.instance functionSetBindeDevice:YES];
    }
}

- (void)caBleDeviceInfo:(CADeviceInfo *)devInfo {
    
}


- (void)caBleDidConnectPeripheral:(CABLeService*)service {
    
    [CARingSDK.instance setCurrentPeripheralService:service];
}

- (void)caBleDidDisconnectPeripheral:(CABLeService*)service {
    
    [CARingSDK.instance setCurrentPeripheralService:nil];

}

- (void)caBleDeviceRealtimeSteps:(nonnull NSNumber *)steps IsDeviceFix:(BOOL)isDeviceFixed { 
    
}


- (void)caBleDeviceRealtimeTemperature:(nonnull NSNumber *)temperature { 
    
}


- (void)caBleFailConnectPeripheral:(nonnull CBPeripheral *)peripheral Error:(nonnull NSError *)error { 
    
}


- (void)caBleHistoryDataCount:(NSInteger)count { 
    
}


- (void)caBleHistoryDataTimeout { 
    
}


- (void)caBleHistorySr03Data:(nonnull CAHistoryDataSR03 *)hisData IsComplete:(BOOL)isComplete { 
    
}


- (void)caBleIsBinded:(BOOL)isBinded { 
    
}


- (void)caBleMeasureDuration:(NSInteger)seconds { 
    
}


- (void)caBleOEMAuthResult:(BOOL)authSucceddful { 
    
}


- (void)caBleRealtimeHRV:(nonnull NSNumber *)hrv BloodOxygen:(nonnull NSNumber *)bloodOxygen HeartRate:(nonnull NSNumber *)hr Status:(REALTIME_STATUS)status { 
    
}


- (void)caBleSN:(nonnull NSString *)sn SnData:(nonnull NSData *)snData { 
    
}

-(void)caScanDeviceDidRefresh:(NSArray<CABLeService *> *)perphelArray
{
    // reconnect after ota image uploaded to device
    for (CABLeService *service in perphelArray) {
        if ([service.macAddress isEqualToString:self.waitRecDeviceMacaddr]) {
            [self.ousideBleDiscovery stopScanning];
            [self.scanTimeoutTimer invalidate];

            [self.ousideBleDiscovery connectCaPeripheral:service];
            break;
        }
    }
    
}







#pragma mark --OTA delegete
- (void)caOtaError:(CAOTA_STATUS_VALUES)errorCode {
    
    WEAK_SELF
    [self showAlertWarningWithTitle:@"Tips" Msg:@"Firmware update failed!" btnOk:@"Ok" OkBLk:^{
        STRONG_SELF
        strongSelf.otaState = CA_OTA_STATE_FINISH;
        if (strongSelf.otaFinishBLK) {
            strongSelf.otaFinishBLK(NO);
        }
        [strongSelf.navigationController popViewControllerAnimated:YES];
    } CancelBtn:nil CancelBlk:nil Compelete:nil];
}

- (void)caOtaFinish:(BOOL)isSuccessful {
    if (!isSuccessful) {
        [self caOtaError:0];
        return;
    }
    
    if (isSuccessful) {
        self.otaState = CA_OTA_STATE_RECONNECTING;
        
        return;
    }
}

- (void)caOtaUpdateProgress:(float)progress {
    
    [self.progressView setProgress:progress animated:YES];
    [self.percentLabel setText:[NSString stringWithFormat:@"%d%%",(int)(progress*100)]];
}

#pragma mark --lazy

-(UILabel *)tipsLabel
{
    if (!_tipsLabel) {
        _tipsLabel = [UILabel new];
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
        _tipsLabel.numberOfLines = 0;
        _tipsLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:20];
        _tipsLabel.textColor = MAIN_BLUE;
    }
    return _tipsLabel;
}
-(UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]init];
    }
    return _progressView;
}

-(UILabel *)percentLabel
{
    if (!_percentLabel) {
        _percentLabel = [UILabel new];
        _percentLabel.textAlignment = NSTextAlignmentCenter;
        _percentLabel.textColor = MAIN_BLUE;
    }
    return _percentLabel;
    
}

@end
